package com.example.demo.controller;

import com.example.demo.entity.Feedback;
import com.example.demo.pojo.PlannerResult;
import com.example.demo.repository.FeedbackRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.utils.ThreadLocalUtil;
import com.example.demo.vo.FeedbackVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/feedback")
public class FeedbackController {

    @Autowired
    FeedbackRepository feedbackRepository;
    @Autowired
    private UserRepository userRepository;

    //根据活动Id找到所有反馈
    @GetMapping("/findallfeedbackbyid")
    public PlannerResult<List<FeedbackVo>> findfeedbackById(@RequestParam("activityid") Integer activityid)
    {
        List<Feedback> feedbacks=feedbackRepository.findAllByActivity_id(activityid);
        List<FeedbackVo> feedbackVos=new ArrayList<>();
        feedbacks.forEach( feedback -> {
            FeedbackVo feedbackVo=new FeedbackVo();
            BeanUtils.copyProperties(feedback,feedbackVo);
            feedbackVo.setUsername(userRepository.findById(feedback.getUser_id()).get().getUsername());
            feedbackVo.setAvatar(userRepository.findById(feedback.getUser_id()).get().getAvatar());

            feedbackVos.add(feedbackVo);
        });
        return PlannerResult.success(feedbackVos);
    }

    //保存反馈

    @PostMapping("/createfeedback")
    public PlannerResult<String> save(@RequestBody FeedbackVo feedbackVo)
    {
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userid=(Integer) map.get("id");

        Feedback feedback1=new Feedback();
        feedback1.setActivity_id(feedbackVo.getActivity_id());
        feedback1.setContext(feedbackVo.getContext());
        feedback1.setUser_id(userid);
        Feedback result=feedbackRepository.save(feedback1);
        if(result.getId() !=null)
        {
            return PlannerResult.success();
        }
        else {
            return PlannerResult.error("提交失败");
        }
    }
}
